package com.example.springboottest.example.io.redirect.appserver.bio;


import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class BIOClient {
    public static void main(String[] args) {
        PrintWriter write = null;
        BufferedReader reader = null;
        Socket socket = null;
        try {
            //向本机8080端口发送请求
            socket = new Socket("127.0.0.1", 8080);
            //根据标准输入构造BufferedReader对象
            BufferedReader clientInput = new BufferedReader(new InputStreamReader(System.in));
            //通过Socket得到输出流，构造BufferedReader对象
            write = new PrintWriter(socket.getOutputStream());
            //通过Socket得到输入流，构造BufferedReader对象
            reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //读取输入信息
            String input = clientInput.readLine();
            while (!StringUtils.equals(input, "exit")) {
                //将输入信息发送到服务端
                write.println(input);
                //刷新输出流，使服务器马上收到请求信息
                write.flush();
                //读取服务器返回信息
                System.out.println("服务器响应为:" + reader.readLine());
                //读取下一条信息
                input = clientInput.readLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            write.close();
            try {
                reader.close();
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
